from rest_framework.viewsets import GenericViewSet
from rest_framework.pagination import PageNumberPagination
from rest_framework.filters import OrderingFilter, SearchFilter
from django_filters.rest_framework import DjangoFilterBackend
from utils.common_mixins import APIListModelMixin, APIRetrieveModelMixin
from .paginations import CommonPageNumberPagination
from .models import CourseCategory, Course, CourseChapter
from .serializers import CourseCategorySerializer, CourseSerializer, CourseChapterSerializer


class CourseCategoryView(GenericViewSet, APIListModelMixin):
    cache_key = 'course_category'
    queryset = CourseCategory.objects.all().filter(is_delete=False, is_show=True).order_by('orders')
    serializer_class = CourseCategorySerializer


class CourseView(GenericViewSet, APIListModelMixin, APIRetrieveModelMixin):
    queryset = Course.objects.all().filter(is_delete=False, is_show=True).order_by('orders')
    serializer_class = CourseSerializer
    pagination_class = CommonPageNumberPagination  # 分页
    # 排序
    filter_backends = [OrderingFilter, DjangoFilterBackend]
    ordering_fields = ['id', 'students', 'price', ]
    # 过滤:按课程分类id号过滤
    filterset_fields = ['course_category']


class CourseChapterView(GenericViewSet, APIListModelMixin):
    # 课程章节和课时
    queryset = CourseChapter.objects.all().filter(is_delete=False, is_show=True)
    serializer_class = CourseChapterSerializer
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ['course']  # 按课程过滤


class CourseSearchView(GenericViewSet, APIListModelMixin):
    queryset = Course.objects.all().filter(is_delete=False, is_show=True).order_by('orders')
    serializer_class = CourseSerializer
    pagination_class = PageNumberPagination  # 分页
    filter_backends = [SearchFilter]
    search_fields = ['name']
